package com.the4man.cnbdw.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by lenovo on 2017/12/12.
 */
public class SplitImage {
    private static final Logger logger = LoggerFactory.getLogger(SplitImage.class);
    private static final int width = 300;
    private static final int height = 300;

    public SplitImage() {
    }

    public static void main(String[] args) throws Exception {
        generateImage("c:/opt/base.jpg", "D:/workspace/project/openlayers/src/main/web/mmap/", -1);
    }

    public static void generateImage(String srcImage, String targetImagePath, int level) throws Exception {
        String _targetImagePath = "";
        if(level <= -1) {
            _targetImagePath = targetImagePath + "/resources/mmap/W/0_0/";
        } else {
            _targetImagePath = targetImagePath + "/resources/mmap/" + level + "/0_0/";
        }

        _targetImagePath = StringUtils.replace(_targetImagePath, "\\", "/");
        _targetImagePath = StringUtils.replace(_targetImagePath, "//", "/");
        srcImage = StringUtils.replace(srcImage, "\\", "/");
        srcImage = StringUtils.replace(srcImage, "//", "/");
        String path = (new File(srcImage)).getParent();
        path = StringUtils.replace(path, "//", "/");
        path = StringUtils.replace(path, "//", "/");
        File dir = new File(_targetImagePath);
        if(dir != null && dir.exists() && dir.isDirectory()) {
            FileUtils.cleanDirectory(dir);
        }

        (new File(_targetImagePath)).mkdirs();
        String tempImage = path + UUID.randomUUID().toString() + ".png";
        thumbnails(srcImage, tempImage, 600, 600);
        cut((File)(new File(tempImage)), _targetImagePath, 300, 300);
    }

    private static void thumbnails(String image, String targetDir, int width, int height) throws IOException {
        logger.info("image:{}, targetDir: {}", image, targetDir);
        Thumbnails.of(new String[]{image}).size(width, height).toFile(targetDir);
    }

    private static ImageDto cut(File sourceFile, String targetDir, int width, int height) throws Exception {
        List<File> list = new ArrayList();
        BufferedImage source = ImageIO.read(sourceFile);
        int sWidth = source.getWidth();
        int sHeight = source.getHeight();
        if(sWidth > width && sHeight > height) {
//            int cols = false;
//            int rows = false;
            int eWidth = 0;
            int eHeight = 0;
            int cols;
            if(sWidth % width == 0) {
                cols = sWidth / width;
            } else {
                eWidth = sWidth % width;
                cols = sWidth / width + 1;
            }

            int rows;
            if(sHeight % height == 0) {
                rows = sHeight / height;
            } else {
                eHeight = sHeight % height;
                rows = sHeight / height + 1;
            }

            String fileName = null;
            File file = new File(targetDir);
            if(!file.exists()) {
                file.mkdirs();
            }

            BufferedImage image = null;
//            int cWidth = false;
//            int cHeight = false;

            for(int i = 0; i < rows; ++i) {
                for(int j = 0; j < cols; ++j) {
                    int cWidth = getWidth(j, cols, eWidth, width);
                    int cHeight = getHeight(i, rows, eHeight, height);
                    image = source.getSubimage(j * width, i * height, cWidth, cHeight);
                    fileName = targetDir + (j - rows / 2) + "_" + -(i - cols / 2 + 1) + ".png";
                    file = new File(fileName);
                    file.getParentFile().mkdirs();
                    System.out.println(fileName);
                    ImageIO.write(image, "png", file);
                    list.add(file);
                }
            }
        }

        return new ImageDto(Integer.valueOf(sWidth), Integer.valueOf(sHeight), list);
    }

    private ImageDto cut(String source, String targetDir, int width, int height) throws Exception {
        return cut(new File(source), targetDir, width, height);
    }

    private static int getWidth(int index, int cols, int endWidth, int width) {
        return index == cols - 1 && endWidth != 0?endWidth:width;
    }

    private static int getHeight(int index, int rows, int endHeight, int height) {
        return index == rows - 1 && endHeight != 0?endHeight:height;
    }
}
